package com.task.quartz.task;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import javax.annotation.Resource;

import com.task.common.redis.RedisKeyConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import com.task.common.core.redis.RedisCache;
import com.task.common.domain.info.CountryInfo;
import com.task.common.info.DeptIdForAuthentication;
import com.task.common.info.DeviceFraudInfo;
import com.task.common.info.DeviceGroupInfo;
import com.task.common.info.FlowFilterInfo;
import com.task.common.info.IpFraudInfo;
import com.task.common.info.PluginInfo;
import com.task.common.info.ProxyInfo;
import com.task.common.info.RelationMissionDeviceFraud;
import com.task.common.info.RelationMissionDeviceGroup;
import com.task.common.info.RelationMissionFlowFilter;
import com.task.common.info.RelationMissionIpFraud;
import com.task.common.info.RelationMissionPlugin;
import com.task.common.info.RelationMissionProxy;
import com.task.common.utils.StringUtils;
import com.task.common.utils.SystemFunctionUtil;
import com.task.common.utils.date.DateConstants;
import com.task.common.utils.date.DateUtil;
import com.task.quartz.mapper.TaskMapper;

/**
 * 定时任务调度测试
 *
 * @author task
 */
@Component("TaskJobService")
public class TaskJobService {

  @Resource
  private TaskMapper taskMapper;

  @Resource
  private RedisCache redisCache;

  public void MultipleParams(String s, Boolean b, Long l, Double d, Integer i) {
    System.out.println(
        StringUtils.format("执行多参方法： 字符串类型{}，布尔类型{}，长整型{}，浮点型{}，整形{}", s, b,
            l, d, i));
  }

  public void Params(String params) {
    System.out.println("执行有参方法：" + params);
  }

  public void NoParams() {
    System.out.println("执行无参方法");
  }

  public void checkTableExist() {
    try {
      checkDataHistoryTable(SystemFunctionUtil.HISTORY_DATA_GET_DETAIL);
    } catch (Exception e) {
      e.printStackTrace();
    }
    try {
      checkMissionHistoryTable(SystemFunctionUtil.HISTORY_MISSION_GET_DETAIL);
    } catch (Exception e) {
      e.printStackTrace();
    }
    try {
      checkDataIndexHistoryTable(SystemFunctionUtil.HISTORY_DATA_GET_INDEX);
    } catch (Exception e) {
      e.printStackTrace();
    }
    //检查重复表
    deleteRepeatTableName();
  }

  private void deleteRepeatTableName() {
    List<String> repeatTableCodes = taskMapper.getRepeatTableCodes();
    if (CollectionUtils.isEmpty(repeatTableCodes)) {
      return;
    }
    taskMapper.deleteRepeatTableCode(repeatTableCodes);
    deleteRepeatTableName();
  }

  private void checkDataIndexHistoryTable(String prefix) {
    for (int i = 0; i < 3; i++) {
      String yyyyMM = DateUtil.dateToStr(DateUtil.addMonth(new Date(), i),
          DateConstants.DATE_FORMAT_YM);
      String tableName = SystemFunctionUtil.getHistoryTableNameByTime(yyyyMM, prefix);
      try {
        Integer c = taskMapper.checkTableExist(tableName);
      } catch (Exception e) {
        //添加表
        taskMapper.createDataIndexHistoryTable(tableName);
        taskMapper.insertHistoryTablesData(tableName, prefix);
      }
    }
    //同步t_history_tables表
    //查询数据库实际存在表
    syncData(prefix);
  }

  private void syncData(String prefix) {
    List<String> tablesInDatabase = taskMapper.getTablesNameByPreFromDatabase(prefix);
    List<String> tablesInTable = taskMapper.getTablesNameByPreFromTable(prefix);
    List<String> deleteTables = new ArrayList<>();
    for (String tit : tablesInTable) {
      if (!tablesInDatabase.contains(tit)) {
        //记录表中有实际数据库没有
        //删除
        deleteTables.add(tit);
      }
    }
    if (!CollectionUtils.isEmpty(deleteTables)) {
      taskMapper.deleteTablesByNames(deleteTables);
    }
  }

  //检测data发送记录表
  private void checkDataHistoryTable(String prefix) {
    for (int i = 0; i < 3; i++) {
      String yyyyMM = DateUtil.dateToStr(DateUtil.addMonth(new Date(), i),
          DateConstants.DATE_FORMAT_YM);
      String tableName = SystemFunctionUtil.getHistoryTableNameByTime(yyyyMM, prefix);
      try {
        Integer c = taskMapper.checkTableExist(tableName);
      } catch (Exception e) {
        //添加表
        taskMapper.createDataHistoryTable(tableName);
        taskMapper.insertHistoryTablesData(tableName, prefix);
      }
    }
    //同步t_history_tables表
    //查询数据库实际存在表
    syncData(prefix);
  }

  //检测mission发送记录表
  private void checkMissionHistoryTable(String prefix) {
    for (int i = 0; i < 3; i++) {
      String yyyyMM = DateUtil.dateToStr(DateUtil.addMonth(new Date(), i),
          DateConstants.DATE_FORMAT_YM);
      String tableName = SystemFunctionUtil.getHistoryTableNameByTime(yyyyMM, prefix);
      try {
        Integer c = taskMapper.checkTableExist(tableName);
      } catch (Exception e) {
        //添加表
        taskMapper.createMissionHistoryTable(tableName);
        taskMapper.insertHistoryTablesData(tableName, prefix);
      }
    }
    //同步t_history_tables表
    //查询数据库实际存在表
    syncData(prefix);
  }

  public void addDeptAuthentication() {
    List<DeptIdForAuthentication> list = taskMapper.selectAddDeptAuthentication();
    String deptIdForAuthenticationKey = RedisKeyConstants.DEPT_ID_FOR_AUTHENTICATION.formatKey();
    for (DeptIdForAuthentication deptIdForAuthentication : list) {
      try {
        redisCache.redisTemplate.opsForValue()
            .setIfAbsent(deptIdForAuthenticationKey + deptIdForAuthentication.getAuthentication(), deptIdForAuthentication.getDeptId());
      }catch (Exception e) {
        e.printStackTrace();
      }
    }
  }

  public void addRelationTable() {

  }

  public void addRelationValue() {
    //data_device_fraud
    List<DeviceFraudInfo> deviceFraudInfos = taskMapper.getAllDeviceFraudInfo();
    if (!CollectionUtils.isEmpty(deviceFraudInfos)) {
      for (DeviceFraudInfo deviceFraudInfo : deviceFraudInfos) {
        redisCache.setCacheObject(RedisKeyConstants.DEVICE_FRAUD_INFO.formatKey(deviceFraudInfo.getCode()), deviceFraudInfo);
      }
    }

    //data_device_group
    List<DeviceGroupInfo> deviceGroupInfos = taskMapper.getAllDeviceGroupInfo();
    if (!CollectionUtils.isEmpty(deviceGroupInfos)) {
      for (DeviceGroupInfo info : deviceGroupInfos) {
        redisCache.setCacheObject(RedisKeyConstants.DEVICE_GROUP_INFO.formatKey(info.getCode()), info);
      }
    }


    //data_flow_filter
    List<FlowFilterInfo> flowFilterInfos = taskMapper.getAllFlowFilterInfo();
    if (!CollectionUtils.isEmpty(flowFilterInfos)) {
      for (FlowFilterInfo info : flowFilterInfos) {
        redisCache.setCacheObject(RedisKeyConstants.FLOW_FILTER_INFO.formatKey(info.getCode()), info);
      }
    }


    //data_ip_fraud
    List<IpFraudInfo> ipFraudInfos = taskMapper.getAllIpFraudInfo();
    if (!CollectionUtils.isEmpty(ipFraudInfos)) {
      for (IpFraudInfo info : ipFraudInfos) {
        redisCache.setCacheObject(RedisKeyConstants.IP_FRAUD_INFO.formatKey(info.getCode()), info);
      }
    }


    //data_plugin
    List<PluginInfo> pluginInfos = taskMapper.getAllPluginInfo();
    if (!CollectionUtils.isEmpty(pluginInfos)) {
      for (PluginInfo info : pluginInfos) {
        redisCache.setCacheObject(RedisKeyConstants.PLUGIN_INFO.formatKey(info.getCode()), info);
      }
    }


    //data_proxy
    List<ProxyInfo> proxyInfos = taskMapper.getAllProxyInfo();
    if (!CollectionUtils.isEmpty(proxyInfos)) {
      for (ProxyInfo info : proxyInfos) {
        redisCache.setCacheObject(RedisKeyConstants.PROXY_INFO.formatKey(info.getCode()), info);
      }
    }


    //国家信息
    List<CountryInfo> countryInfos= taskMapper.getAllCountryInfo();
    if (!CollectionUtils.isEmpty(countryInfos)) {
      for (CountryInfo info : countryInfos) {
        redisCache.setCacheObject(RedisKeyConstants.COUNTRY_INFO.formatKey(info.getCode()), info);
      }
    }

  }

  public void initRedis() {
    redisCache.deleteObject("MISSION_SUCCESS_HISTORY_KEY");
    redisCache.deleteObject("MISSION_FAILED_HISTORY_KEY");
    redisCache.deleteObject("INIT_MISSION_REDIS_KEY");
    redisCache.deleteObject("CHANGE_MISSION_NORMAL_STATUS_KEY");
    redisCache.deleteObject("MISSION_SUCCESS_HISTORY_KEY");
    redisCache.deleteObject("DATA_INCREMENT");
  }
}
